// personal/payDeatil/index.js
const app = getApp()
import {
  toast,
  distance
} from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentIndex: 0,
    payPrice: '',
    info: {},
    date: `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()}`,
    effectiveDate: '',
    cardNum: 0,
    shareNum: 0,
    paytype: 1,
    cardid: '',
    yearId: '412b9cbf7c5e48ba8093730061366afd',
    cansendcount: 0,
    cards: [],
    yearCard: false,
    enterprise: '',
    id: '',
    from: '',
    tabIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData(options)
    this.renew(options)
    this.getCard()
  },
  getCard() {
    const result = this.data.cards
    app.$api.common.findCard()
      .then((res) => {
        const data = res.data
        console.log(data.data)
        this.setData({
          cards: data.data
        })
        this.getPrice()
        this.initDate()
      }).catch((res) => {
        toast('请稍后再试', 1000)
      })
  },
  initData(options) {
    if (options.from) {
      this.setData({
        from: options.from,
        id: options.id
      })
    }
    const distance = this.calcDistance(options)
    const info = Object.assign({}, options, {
      distance
    })
    this.setData({
      info,
      cansendcount: wx.getStorageSync('userInfo').cansendcount
    })
    if (Number(options.index) === 1) {
      app.$api.common.commonFindName({
          code: options.entType
        })
        .then((s) => {
          const data = s.data
          this.setData({
            enterprise: data.name
          })
          console.log(this.data.enterprise)
        }).catch((e) => {
          toast('请稍后再试', 1000)
        })
    }
  },
  initDate() {
    const currentIndex = this.data.currentIndex
    console.log(currentIndex)
    let effectiveDate
    if (typeof currentIndex === 'number') {
      const {
        duration
      } = this.data.cards[currentIndex]
      const month = new Date().getMonth() + 1 + duration
      if (month > 12) {
        effectiveDate = `${new Date().getFullYear() + 1}-${month - 12}-${new Date().getDate()}`

      } else {
        effectiveDate = `${new Date().getFullYear()}-${month}-${new Date().getDate()}`
      }
    } else {
      console.log('null-currentIndex')
      effectiveDate = `${new Date().getFullYear() + 1}-${new Date().getMonth() + 1}-${new Date().getDate()}`
    }
    this.setData({
      effectiveDate,
    })
    console.log(this.data.effectiveDate)
  },
  // 续费参数
  renew(options) {
    const {
      index
    } = options
    this.setData({
      tabIndex: index
    })
    if (options.id) {
      Number(index) === 0 ? this.getRentDetail(options.id, index) : Number(index) === 1 ? this.getSellDetail(options.id, index) : this.getMaintainDetail(options.id, index)
    }
  },
  getRentDetail(id, index) {
    app.$api.index.rentDetail({
        id
      })
      .then((res) => {
        const data = res.data
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance
        })
        console.log(info + '11')
        this.setData({
          info
        })
        console.log(this.data.info)
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getSellDetail(id, index) {
    app.$api.index.saleDetail({
        id
      })
      .then((res) => {
        const data = res.data
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance
        })
        this.setData({
          info
        })
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getMaintainDetail(id, index) {
    app.$api.index.maintainDetail({
        id
      })
      .then((res) => {
        const data = res.data
        const distance = this.calcDistance(data)
        const info = Object.assign({}, data, {
          index,
          distance
        })
        this.setData({
          info
        })
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getPrice() {
    const num = wx.getStorageSync('userInfo').cansendcount
    const code = 'sendPriceScale'
    const shardCode = 'recommendUserCount'
    Promise.all([app.$api.common.commonFindName({
        code
      }), app.$api.common.commonFindName({
        code: shardCode
      })])
      .then((res) => {
        const share = res[1].data
        this.setData({
          payPrice: this.data.cards[0].price,
          cardid: this.data.cards[0].id,
          cardNum: num,
          shareNum: share.name
        })
      }).catch((res) => {
        toast('请稍后再试', 1000)
      })
  },
  calcDistance(item) {
    const locationA = {
      lat: wx.getStorageSync('location').lat,
      lng: wx.getStorageSync('location').lng
    }
    const locationB = {
      lat: Number(item.lat),
      lng: Number(item.lon)
    }
    const distanceValue = distance(locationA, locationB)
    return distanceValue
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const userid = wx.getStorageSync('userInfo').userid
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '山河笑',
      path: `/pages/index/index?userid=${userid}`
    }
  },
  bindCurrent(e) {
    const {
      index
    } = e.currentTarget.dataset
    this.setData({
      currentIndex: index,
      yearCard: false,
      payPrice: this.data.cards[index].price,
      cardid: this.data.cards[index].id,
      paytype: 1
    })
    this.initDate()
  },
  bindCurrentSecond() {
    this.setData({
      yearCard: true,
      paytype: 2,
      currentIndex: null,
      payPrice: '年卡支付'
    })
    this.initDate()
  },
  bindPerson() {
    const url = '/personal/person/index'
    wx.navigateTo({
      url,
    })
  },
  bindPay() {
    if (this.data.from !== '') {
      this.getRenew()
    } else {
      const paytype = this.data.paytype
      const {
        index
      } = this.data.info
      const cansendcount = wx.getStorageSync('userInfo').cansendcount
      const shareNum = this.data.shareNum
      if (cansendcount <= 0 && paytype === 2) {
        wx.showModal({
          title: '温馨提示',
          content: `你还没有年卡，请将本程序分享给好友，累计${shareNum}次，即可获得1张年卡`,
          showCancel: false
        })
        return false
      }

      Number(index) === 0 ? this.addType() : Number(index) === 1 ? this.addSell() : this.addMaintain()
    }
  },
  addType() {
    const paytype = this.data.paytype
    const cardid = paytype === 2 ? this.data.yearId : this.data.cardid
    const {
      equType,
      equName,
      shortPrice,
      longPrice,
      companyName,
      linkName,
      phone,
      detailedAddress,
      freeDate,
      equImgUrl,
      equprofile,
      equattr
    } = this.data.info
    const lon = Number(this.data.info.lon)
    const lat = Number(this.data.info.lat)
    const equimgurlOld = equImgUrl.split(',').map((item) => {
      return JSON.parse(item).fileUrl
    })
    const equimgurl = equimgurlOld.join(',')
    const equtype = equType
    const equname = equName
    const shortprice = shortPrice
    const longprice = longPrice
    const companyname = companyName
    const linkname = linkName
    const detailedaddress = detailedAddress
    const freedate = freeDate
    console.log(JSON.parse(equattr))
    app.$api.publish.rentAdd({
        equtype,
        equname,
        shortprice,
        longprice,
        companyname,
        linkname,
        phone,
        lon,
        lat,
        detailedaddress,
        equimgurl,
        freedate,
        paytype,
        cardid,
        equprofile,
        equattr
      })
      .then((res) => {
        const data = res.data
        if (paytype === 2) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          })
          this.setData({
            cansendcount: cansendcount - 1
          })
          this.getUser()
        } else {
          wx.requestPayment({
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.sign,
            success(data) {
              wx.navigateTo({
                url: '/personal/person/index',
              })
            },
            fail(data) {}
          })
        }
      })
  },
  addSell() {
    const paytype = this.data.paytype
    const cardid = paytype === 2 ? this.data.yearId : this.data.cardid
    const {
      entType,
      entScope,
      companyName,
      linkName,
      phone,
      detailedAddress,
      freeDate,
      equImgUrl
    } = this.data.info
    const lon = Number(this.data.info.lon)
    const lat = Number(this.data.info.lat)
    const equimgurlOld = equImgUrl.split(',').map((item) => {
      return JSON.parse(item).fileUrl
    })
    const imgurl = equimgurlOld.join(',')
    const enttype = entType
    const entscope = entScope
    const companyname = companyName
    const linkname = linkName
    const detailedaddress = detailedAddress
    const freedate = freeDate
    const entprofile = this.data.info.entProfile
    app.$api.publish.saleAdd({
        enttype,
        entscope,
        companyname,
        linkname,
        phone,
        lon,
        lat,
        detailedaddress,
        imgurl,
        paytype,
        cardid,
        entprofile
      })
      .then((res) => {
        const data = res.data
        if (paytype === 2) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          })
          this.setData({
            cansendcount: cansendcount - 1
          })
          this.getUser()
        } else {
          wx.requestPayment({
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.sign,
            success(data) {
              wx.navigateTo({
                url: '/personal/person/index',
              })
            },
            fail(data) {}
          })
        }
      })
  },
  addMaintain() {
    const paytype = this.data.paytype
    const cardid = paytype === 2 ? this.data.yearId : this.data.cardid
    const {
      maintainScope,
      companyName,
      linkName,
      phone,
      detailedAddress,
      freeDate,
      equImgUrl
    } = this.data.info
    const lon = Number(this.data.info.lon)
    const lat = Number(this.data.info.lat)
    const equimgurlOld = equImgUrl.split(',').map((item) => {
      return JSON.parse(item).fileUrl
    })
    const imgurl = equimgurlOld.join(',')
    const maintainscope = maintainScope
    const companyname = companyName
    const linkname = linkName
    const detailedaddress = detailedAddress
    const freedate = freeDate
    const entprofile = this.data.info.entProfile
    console.log(cardid)
    app.$api.publish.maintainAdd({
        maintainscope,
        companyname,
        linkname,
        phone,
        lon,
        lat,
        detailedaddress,
        imgurl,
        entprofile,
        paytype,
        cardid
      })
      .then((res) => {
        const data = res.data
        if (paytype === 2) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          })
          this.setData({
            cansendcount: cansendcount - 1
          })
          this.getUser()
        } else {
          wx.requestPayment({
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.sign,
            success(data) {
              wx.navigateTo({
                url: '/personal/person/index',
              })
            },
            fail(data) {}
          })
        }
      })
  },
  getUser() {
    const userInfo = wx.getStorageSync('userInfo')
    const id = userInfo.userid
    app.$api.user.detail({
        id
      })
      .then((res) => {
        const data = res.data
        const newUserInfo = Object.assign({}, userInfo, {
          ...data
        })
        wx.setStorageSync('userInfo', newUserInfo)
        wx.reLaunch({
          url: '/pages/index/index'
        })
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  // 续费
  getRenew() {
    const {
      paytype
    } = this.data
    const infoid = this.data.id
    const id = paytype === 2 ? this.data.yearId : this.data.cardid
    const infotype = Number(this.data.info.index) + 1
    const cansendcount = wx.getStorageSync('userInfo').cansendcount
    const shareNum = this.data.shareNum
    if (cansendcount <= 0 && paytype === 2) {
      wx.showModal({
        title: '温馨提示',
        content: `你还没有年卡，请将本程序分享给好友，累计${shareNum}次，即可获得1张年卡`,
        showCancel: false
      })
      return false
    }
    app.$api.user.renew({
        id,
        infoid,
        infotype,
        paytype
      })
      .then((res) => {
        const data = res.data
        if (paytype === 2) {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1000
          })
          this.setData({
            cansendcount: cansendcount - 1
          })
          this.getUser()
          wx.navigateTo({
            url: '/personal/person/index',
          })
        } else {
          wx.requestPayment({
            timeStamp: data.timestamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.sign,
            success(data) {
              wx.showToast({
                title: '续费成功',
                icon: 'success',
                duration: 1000
              })
              wx.navigateTo({
                url: '/personal/person/index',
              })
            },
            fail(data) {}
          })
        }
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  // 未支付，再次支付
})